package com.easylinkin.core.utils;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @author kyj
 * @date 2024/5/29 19:58
 */
public class HttpFileUtils {
    public static <T> ResponseEntity<byte[]> exportFile(byte[] bytes, String filename) {

        try {
            filename = URLEncoder.encode(filename, String.valueOf(StandardCharsets.UTF_8)).replaceAll("\\+", "%20");

            return ResponseEntity.ok()
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .header(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, HttpHeaders.CONTENT_DISPOSITION)
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + filename)
                    .body(bytes);

        } catch (IOException e) {
            throw new RuntimeException("导出失败");
        }
    }

    public static void setFileResponse(HttpServletResponse response, String filename) throws UnsupportedEncodingException {
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        filename = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + filename);
    }

    /**
     * 请求下载文件
     *
     * @param url      请求下载文件地址
     * @param timeout  超时时间
     * @return HttpResponse
     * @since 5.4.1
     */
    public static HttpResponse requestDownload(String url, int timeout) {
        Assert.notBlank(url, "[url] is blank !");

        final HttpResponse response = HttpUtil.createGet(url, true)
                .timeout(timeout)
                .executeAsync();

        if (response.isOk()) {
            return response;
        }

        throw new HttpException("Server response error with status code: [{}]", response.getStatus());
    }

    /**
     * 从Content-Disposition头中获取文件名
     *
     * @return 文件名，empty表示无
     */
    public static String getFileNameFromDisposition(HttpResponse httpResponse) {
        String fileName = null;
        final String disposition = httpResponse.header(Header.CONTENT_DISPOSITION);
        if (StrUtil.isNotBlank(disposition)) {
            fileName = ReUtil.get("filename=\"(.*?)\"", disposition, 1);
            if (StrUtil.isBlank(fileName)) {
                fileName = StrUtil.subAfter(disposition, "filename=", true);
            }
        }
        return fileName;
    }
}
